<template>
  <div class="container">
    <div class="auto">
      <div class="rule_wrap">
        <div class="crumb">
          <span>新建留言</span>
        </div>
        <a-spin :spinning="confirmLoading">
          <div class="msg_form">
            <a-form :form="form">
              <h6 class="tt">新建留言 <em class="fz"><i>*</i> 为必填项</em></h6>
              <div class="box">
                <a-row>
                  <a-form-item label="留言标题" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input
                      placeholder="请输入留言标题"
                      v-decorator="['title', validatorRules.title ]"/>
                  </a-form-item>
                </a-row>
                <a-row>
                  <a-form-item label="留言正文" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <j-editor v-decorator="['content',validatorRules.content]" triggerChange :max_height="300"
                              placeholder="请输入留言正文"></j-editor>
                  </a-form-item>
                </a-row>
                <a-row>
                  <a-form-item label="邮箱地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input
                      placeholder="请输入邮箱地址"
                      v-decorator="['email', validatorRules.email ]"/>
                  </a-form-item>
                </a-row>
                <a-row>
                  <a-form-item label="验证码" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input
                      style="width: 40%; display: inline-block; margin-right: 10px;"
                      placeholder="请输入验证码"
                      v-decorator="['captcha', validatorRules.captcha ]"/>
                    <img :src="imgUrl" alt="验证码" style="height: 32px; width: 100px; cursor: pointer;"
                         @click="changeUuid">
                  </a-form-item>

                </a-row>
                <a-row style="margin-top: 20px;">
                  <a-col span="2" offset="4">
                    <a-button type="primary" @click="submit">发布</a-button>
                  </a-col>
                  <a-col span="6">
                    <a-button type="primary" @click="priview">预览</a-button>
                  </a-col>
                  <a-col span="2" offset="8">
                    <a-button @click="goBack">取消</a-button>
                  </a-col>
                </a-row>
              </div>
            </a-form>
          </div>
        </a-spin>
        <priviewMessage ref="priviewMessage"></priviewMessage>
      </div>
    </div>
  </div>
</template>

<script>
import priviewMessage from './modules/PreviewMessage'
import '../../../public/css/style.css';
import { postAction } from '@/api/manage'
import pick from 'lodash.pick'
import JEditor from '@/moduleCompontent/JEditor'
import BASE_URL from '../../../config'
export default {
  name: 'AddMessageBook',
  beforeRouteEnter (to, from, next) {
    window.scrollTo(0, 0);
    next();
  },
  components: {
    JEditor,
    priviewMessage
  },
  data () {
    return {
      confirmLoading: false,
      uuid: '',
      labelCol: {
        xs: {span: 24},
        sm: {span: 5}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      form: this.$form.createForm(this),
      validatorRules: {
        title: {rules: [{required: true, message: '请输入留言标题!' }]},
        content: {rules: [{required: true, message: '请输入留言正文!' }]},
        email: {rules: [{required: true, message: '请输入邮箱地址!' }, { validator: this.validateEmail }]},
        captcha: {rules: [{required: true, message: '请输入验证码!' }]}
      }
    };
  },
  created() {
    this.uuid = this.generateUUID()
    this.form.setFieldsValue(pick(this.model, 'title','content', 'email', 'captcha'))
  },
  computed: {
    imgUrl() {
      let url = BASE_URL + '/messagebook/captcha.jpg?uuid=' + this.uuid
      return url
    }
  },
  methods: {
    NowTime() {
      //获取年月日
      let time = new Date();
      let year = time.getFullYear();
      let month = time.getMonth() + 1;
      let day = time.getDate();

      //获取时分秒
      let h = time.getHours();
      let m = time.getMinutes();
      let s = time.getSeconds();

      //检查是否小于10
      h = this.check(h);
      m = this.check(m);
      s = this.check(s);
      return year+ '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
    },
    check(i) {
      let num;
      i<10?num="0"+i:num=i
      return num
    },
    priview() {
      this.form.validateFields((err, value) => {
        if (!err) {
          let params = {
            title: this.form.getFieldValue('title'),
            content: this.form.getFieldValue('content'),
            // createDate: this.NowTime,
            email: this.form.getFieldValue('email')
          }
          params.createDate = this.NowTime()
          this.$refs.priviewMessage.show(params)
        }
      })
    },
    // 确认邮箱
    validateEmail(rule, value, callback){
      if(!value){
        callback()
      }else{
        if(new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)){
          callback()
        }else{
          callback("请输入正确格式的邮箱!")
        }
      }
    },
    changeUuid() {
       this.uuid = this.generateUUID()
    },
    goBack() {
      this.$router.go(-1)
    },
    // 生成唯一标识符
    generateUUID() {
      var d = new Date().getTime();
      if (window.performance && typeof window.performance.now === "function") {
          d += performance.now(); //use high-precision timer if available
      }
      var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          var r = (d + Math.random() * 16) % 16 | 0;
          d = Math.floor(d / 16);
          return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
      });
      return uuid;
    },
    submit() {
      let self = this
      this.form.validateFields((err, value) => {
        if (!err) {
          self.confirmLoading = true
          let formData = Object.assign({}, value);
          formData.uuid = self.uuid
          postAction('/messagebook/save', formData).then(res => {
            if(res.code == 0) {
              self.$message.success(res.msg)
              self.confirmLoading = false
              self.$router.push({path: '/messageBook'})
            } else {
              self.$message.error(res.msg)
              self.confirmLoading = false
            }
          })
        }
      })
    }
  }
};
</script>

<style lang="less" scoped>
  .no-data {
      color: rgba(0, 0, 0, .25);
      text-align: center;
      line-height: 64px;
      font-size: 16px;

      i {
        font-size: 24px;
        margin-right: 16px;
        position: relative;
        top: 3px;
      }
    }
</style>
